package org.beetl.ormunit;

import java.util.List;


import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;

/**
 * Beetlsql 
 * @author lijiazhi
 *
 */
public class BeetlSQLDatabaseAccess implements DBAccess {

	SQLManager sqlManager ;
	BeetlSQLMapper mapper;
	public BeetlSQLDatabaseAccess(SQLManager sql,BeetlSQLMapper mapper){
		this.sqlManager = sql;
		this.mapper = mapper;
		
	}
	
	@Override
	public void save(Class z,Object o) {
		sqlManager.insert(z, o,true);
		

	}

	@Override
	public Object findById(Class clz,Object id) {
		return sqlManager.unique(clz, id);
	}

	@Override
	public List<Object> query(Class clz,String tableName,String where,VariableTable vars) {
		
		StringBuilder sb = new StringBuilder(" select * from ");
		sb.append(tableName).append(" where ").append(where);
		String sql =sb.toString();
		Object[] ret = ClassUtil.parseSql(sql);
		List<String> para = (List<String>)ret[0];
		String jdbcSql = (String)ret[1];
		Object[] sqlParas = new Object[para.size()];
		for(int i=0;i<para.size();i++){
			sqlParas[i]= vars.find(para.get(i));
		}
		return sqlManager.execute(new SQLReady(jdbcSql,sqlParas), clz);
	}
	@Override
	public Mapper getMapper() {
		return this.mapper;
	}
	
	

}
